package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.heima.article.dto.ArticleStreamMessage;
import com.heima.article.dto.UpdateArticleMessage;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.kstream.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.util.StringUtils;

import java.time.Duration;

@EnableBinding(value = ArticleProcess.class)
public class ArticleListener {
    @Value("${commit.time}")
    private String commitTime;

    //指定接收消息的主题
    @StreamListener(value = "article_behavior")
    //指定发送结果的主题
    @SendTo(value = "article_result")
    public KStream<String, String> process(KStream<String, String> input) {
        // 接收到的消息格式为 UpdateArticleMessage
        KStream<String, String> map = input.map(new KeyValueMapper<String, String, KeyValue<String, String>>() {
            @Override
            public KeyValue<String, String> apply(String key, String value) {
                // key 是接收消息的key,暂时不关心
                // value 是json = {"articleId":1540597913363701761,"type":1,"add":1}
                // 解析json,提取文章id
                System.out.println("接收到消息: " + value);
                UpdateArticleMessage message = JSON.parseObject(value, UpdateArticleMessage.class);
                Long articleId = message.getArticleId();
                //构建返回的键值对
                return new KeyValue<>(articleId.toString(), value);
            }
        });
        //根据每一篇文章的id进行分组
        KGroupedStream<String, String> groupByKey = map.groupByKey();
        //统计时间窗口的数据
        TimeWindowedKStream<String, String> windowedBy = groupByKey.windowedBy(TimeWindows.of(Duration.ofMillis(Long.parseLong(commitTime))));
        //进行聚合处理
        Initializer<String> initializer = new Initializer<String>() {
            @Override
            public String apply() {
                //在同一个窗口内,第一次收到消息,返回的聚合结果
                return null;
            }
        };
        Aggregator<String, String, String> aggregator = new Aggregator<String, String, String>() {
            @Override
            public String apply(String key, String value, String aggregate) {
                // 每次接收到消息,都在这个方法内执行一遍
                // key 是上面自定义的KeyValue中的key --> 文章id
                // value 是上面自定义的KeyValue中的value --> json = {"articleId":1540597913363701761,"type":1,"add":1}
                // aggregate 是在同一个时间窗口内上一次聚合的结果
                // 聚合处理的结果是 ArticleStreamMessage
                System.out.println("开始本次消息的处理: " + value);
                System.out.println("上一次聚合的结果: " + aggregate);
                ArticleStreamMessage message = null;
                //判断上一次的聚合是否为空
                if (StringUtils.isEmpty(aggregate)) {
                    //如果为空,构建新的结果
                    message = new ArticleStreamMessage();
                    message.setArticleId(Long.parseLong(key));
                } else {
                    //如果不为空,结果从上一次聚合的结果中取
                    message = JSON.parseObject(aggregate, ArticleStreamMessage.class);
                }

                //提取本次接受的消息
                UpdateArticleMessage updateArticleMessage = JSON.parseObject(value, UpdateArticleMessage.class);
                //处理本次消息的更新,操作类型 0 阅读 1 点赞 2 评论 3 收藏
                switch (updateArticleMessage.getType()) {
                    case 0:
                        message.setView(message.getView() + updateArticleMessage.getAdd());
                        System.out.println("阅读量增加: " + updateArticleMessage.getAdd());
                        break;
                    case 1:
                        message.setLike(message.getLike() + updateArticleMessage.getAdd());
                        System.out.println("点赞量增加: " + updateArticleMessage.getAdd());
                        break;
                    case 2:
                        message.setComment(message.getComment() + updateArticleMessage.getAdd());
                        System.out.println("评论量增加: " + updateArticleMessage.getAdd());
                        break;
                    case 3:
                        message.setCollect(message.getCollect() + updateArticleMessage.getAdd());
                        System.out.println("收藏量增加: " + updateArticleMessage.getAdd());
                        break;
                }
                // 将本次更新的结果保存到聚合的中间结果
                String jsonString = JSON.toJSONString(message);
                System.out.println("本次聚合完成结果: " + jsonString);
                return jsonString;
            }
        };
        KTable<Windowed<String>, String> aggregate = windowedBy.aggregate(initializer, aggregator);

        //处理结果数据
        KStream<String, String> resultMap = aggregate.toStream().map(new KeyValueMapper<Windowed<String>, String, KeyValue<String, String>>() {
            @Override
            public KeyValue<String, String> apply(Windowed<String> key, String value) {
                System.out.println("时间窗口最终处理结果: " + value);
                return new KeyValue<>(key.key(), value);
            }
        });
        // 最终发送到结果的value是 ArticleStreamMessage转换成json格式
        return resultMap;

    }
}
